const express = require('express')
const { resolve, join } = require('path')
const UPLOAD_DIR = resolve( __dirname, './target')
const fse = require('fs-extra')
const multer = require('multer')

const app = express()
app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*')
  res.header("Access-Control-Allow-Headers", "Content-Type, Content-Length, Authorization, Accept, X-Requested-With")
  res.header("Access-Control-Allow-Methods", "PUT, POST, GET, DELETE, HEAD, OPTIONS")
  if (req.method == 'OPTION') { 
    res.send('ok')
    return 
  }
  next()
})

const storage = multer.diskStorage({
  destination: async (req, file, cb) => {
    console.log(file);
    const dir_name = file.fieldname.split('-')[0]
    // console.log(dir_name);
    const chunkDir = resolve(UPLOAD_DIR, dir_name)
    // console.log(chunkDir);

    if (!fse.existsSync(chunkDir)) {
      await fse.mkdirs(chunkDir)
    }
    cb(null, chunkDir)
  },
  filename: (req, file, cb) => {
    // console.log('file', file);
    cb(null, file.fieldname)
  }
})
const upload = multer({ storage })
app.post('/', upload.any(), async (req, res) => {
  console.log(req.file);
})
app.listen(3001, _ => console.log('http://127.0.0.1:3001'))